type Task<T = any> = () => Promise<T> | T

export default class AsyncQueue<T = any> {
    private queue: Task<T>[] = []
    private running = false

    offer(task: Task<T>) {
        this.queue.push(task)
        this.run()
    }

    isEmpty() { return this.queue.length === 0 }

    private async run() {
        if (this.running) return
        this.running = true
        while (this.queue.length) {
            const job = this.queue.shift()!
            try { await job() } catch (e) { console.error('Queue task error:', e) }
        }
        this.running = false
    }
}
